package com.huajx.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huajx.core.kit.HttpKit;
import com.huajx.tuopuda.client.udp.TuopudaClient2;
import com.huajx.tuopuda.client.udp.TuopudaMessage;



/**
 * 向平台端发送记录
 * @author Administrator
 *
 */
public class UdpSentRecord {
	  private static final Logger logger = LoggerFactory.getLogger(UdpSentRecord.class);

	public static UdpSentRecord dao=new UdpSentRecord();
	
	public static Map<String,String> map=new HashMap<>();
	
	
	public void createMap(TuopudaMessage message){
		  if(message==null){
			  return;
		  }
		  int cardId = message.getCarId();//学生八位卡号
		  int direct = message.getDirect();//学生八位卡号
		  String date = dateFormat(message.getDate(), "yyMMddHHmmss");//考勤时间
		  String keyDate = dateFormat(message.getDate(), "yyMMddHHmm");
		  String key=keyDate+"-"+cardId+"-"+direct;//Map的key
		  System.out.println("命令键值对"+key);
		  String json = map.get(key);
		  json="{\"cardId\":\"#cardId\",\"direct\":\"#direct\",\"date\":\"#date\"}";
		  json=json.replace("#cardId", String.valueOf(cardId)).replace("#direct", String.valueOf(direct))
				  .replace("#date", date);
		  map.put(key, json);
	}
	
	
	/**
	 * 拼接发送平台的
	 */
	public void sendJson(){
		if(map.size()<=0){
			return ;
		}
		StringBuffer buffer=new StringBuffer("[");
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			String value = map.get(key);
			if(value.length()<=0){
				continue;
			}
			buffer.append(value);
			buffer.append(",");
		}
		String records=buffer.toString().substring(0,buffer.length()-1)+"]";
		if(records.length()>10){
            logger.info("向平台端传输数据{}个！", map.size());
            try {
            	  HttpKit.post("http://127.0.0.1:8080/wechat/di/personsattendance/updPersons", records);
            	 //HttpKit.post("http://106.14.20.39:80/wechat/di/personsattendance/updPersons", records);
			} catch (Exception e) {
				// TODO: handle exception
				logger.info("向平台端传输数据{}个,失败,平台端链接信息错误！", map.size());
			}
           
		}
	}
	
	
	/**
	 * 将时间转换为字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String dateFormat(Date date,String format){
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}
	
	
	
	
	
}
